//
//  XTOAuthTabVC.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/11.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit
import SVProgressHUD

//新浪微博的appKey
let WeiboAppKey = "4098451793"
//授权回调页(用户同意授权后，跳转到的页面)
let WeiboRedirect_Uri = "http://www.baidu.com"
//App Secret
let WeiboAppSecret = "ce473dcf8b9a89bdedf297ed2ec1e0eb"

class XTOAuthTabVC: UITableViewController {

    private lazy var webView:UIWebView = UIWebView()
    
    //自定义view
    override func loadView() {
        webView.delegate = self
        
        view = webView
    }
    
    override func viewDidLoad() {
        //请求登陆地址
        let url:String = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        let request = NSURLRequest(URL: NSURL(string: url)!)
        setupNavUI()
        
        //加载登陆界面
        webView.loadRequest(request)
    }
    
    
    private func setupNavUI(){
    navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "取消", fontSize: 15, target: self, action: "cancelAction")
    navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "自动填充", fontSize: 15, target: self, action: "autoFillAction")
    navigationController?.title = "登陆微博"
    }
    
    
    //  MARK: -点击事件 -
    @objc private func cancelAction(){
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillAction(){
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '2364090304@qq.com'; document.getElementById('passwd').value = 'w.a.m.m1314'")
    }

}


extension XTOAuthTabVC : UIWebViewDelegate{

    //将要加载webView时调用的方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("弹出登陆授权页面时发送的请求URL\(request.URL?.absoluteString)")
        
        guard let url = request.URL else{
        //当url为空时，不能进行加载
            return false
        }
        
        //请求的地址中若不含有授权回调页，则不是我们需要的页面
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri){
        return true
        }
        
        if let query = url.query where query.hasPrefix("code="){
        let code = query.substringFromIndex("code=".endIndex)
            
        XTUserAccountViewModel.sharedUserAccount.requestAccessToken(code, complete: { (isSuccess) -> () in
            if isSuccess {
            print("登录成功")
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    //发送变更根控制器的通知

                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                })
                
            }else{
            SVProgressHUD.showSuccessWithStatus("登陆失败")
            }
        })
            
        }else{
        //点击取消授权按钮时，关闭弹出的webView
            dismissViewControllerAnimated(true, completion: nil)
        
        }
        
        
        
        return false
    }
    
    
    //开始加载webView时调用的方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //结束加载webView时调用的方法
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载webView报错时调用的方法
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    

}